<template>
  <view class="food-recognition">
    <view class="page-header">
      <text class="page-title">食物识别与营养分析</text>
      <text class="page-subtitle">拍照或上传图片，获取详细营养信息</text>
    </view>

    <!-- 上传区域 -->
    <view class="upload-section">
      <view v-if="!selectedImage" class="upload-area">
        <view class="upload-icon">📷</view>
        <text class="upload-title">上传食物图片</text>
        <text class="upload-subtitle">支持JPG、PNG格式，最大5MB</text>
        <view class="upload-buttons">
          <view class="upload-btn primary" @tap="takePhoto">
            <text class="btn-text">📷 拍照</text>
          </view>
          <view class="upload-btn secondary" @tap="chooseImage">
            <text class="btn-text">📁 相册</text>
          </view>
        </view>
      </view>

      <view v-else class="image-preview">
        <image :src="selectedImage" class="preview-image" mode="aspectFill" @tap="previewImage"  />
        <view v-if="isAnalyzing" class="analyzing">
          <view class="spinner"></view>
          <text class="analyzing-text">正在分析营养成分...</text>
        </view>
        <view class="reset-btn" @tap="resetAnalysis">
          <text class="reset-text">重新选择</text>
        </view>
      </view>
    </view>

    <!-- 营养分析结果 -->
    <view v-if="nutritionData" class="nutrition-results">
      <view class="result-header">
        <text class="result-title">⚡ 营养成分分析</text>
      </view>
      
      <view class="food-info">
        <text class="food-name">{{ nutritionData.name }}</text>
        <text class="calories">{{ nutritionData.calories }} 卡路里</text>
        <text class="serving">每100克</text>
      </view>

      <view class="nutrition-grid">
        <view class="nutrition-item">
          <view class="nutrition-header">
            <text class="nutrition-label">蛋白质</text>
            <text class="nutrition-value">{{ nutritionData.protein }}g</text>
          </view>
          <view class="progress-bar">
            <view 
              class="progress-fill protein" 
              :style="{ width: getProgressValue(nutritionData.protein, 20) + '%' }"
            ></view>
          </view>
        </view>

        <view class="nutrition-item">
          <view class="nutrition-header">
            <text class="nutrition-label">碳水化合物</text>
            <text class="nutrition-value">{{ nutritionData.carbs }}g</text>
          </view>
          <view class="progress-bar">
            <view 
              class="progress-fill carbs" 
              :style="{ width: getProgressValue(nutritionData.carbs, 50) + '%' }"
            ></view>
          </view>
        </view>

        <view class="nutrition-item">
          <view class="nutrition-header">
            <text class="nutrition-label">脂肪</text>
            <text class="nutrition-value">{{ nutritionData.fat }}g</text>
          </view>
          <view class="progress-bar">
            <view 
              class="progress-fill fat" 
              :style="{ width: getProgressValue(nutritionData.fat, 20) + '%' }"
            ></view>
          </view>
        </view>

        <view class="nutrition-item">
          <view class="nutrition-header">
            <text class="nutrition-label">膳食纤维</text>
            <text class="nutrition-value">{{ nutritionData.fiber }}g</text>
          </view>
          <view class="progress-bar">
            <view 
              class="progress-fill fiber" 
              :style="{ width: getProgressValue(nutritionData.fiber, 10) + '%' }"
            ></view>
          </view>
        </view>
      </view>

      <view class="additional-info">
        <view class="info-tag">
          <text class="tag-text">💧 糖分 {{ nutritionData.sugar }}g</text>
        </view>
        <view class="info-tag">
          <text class="tag-text">🧂 钠 {{ nutritionData.sodium }}mg</text>
        </view>
      </view>

      <view class="health-advice">
        <text class="advice-title">💡 健康建议</text>
        <text class="advice-text">{{ nutritionData.advice }}</text>
      </view>

      <!-- 保存记录按钮 -->
      <view class="action-buttons">
        <view class="action-btn primary" @tap="saveRecord">
          <text class="btn-text">保存到饮食记录</text>
        </view>
        <view class="action-btn secondary" @tap="shareResult">
          <text class="btn-text">分享结果</text>
        </view>
      </view>
    </view>

    <!-- 常见食物 -->
    <view class="sample-foods">
      <text class="sample-title">常见食物</text>
      <view class="foods-grid">
        <view 
          v-for="food in sampleFoods" 
          :key="food.name"
          class="food-item"
          @tap="selectSampleFood(food)"
        >
          <text class="food-emoji">{{ food.emoji }}</text>
          <text class="food-name">{{ food.name }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'

const selectedImage = ref(null)
const isAnalyzing = ref(false)
const nutritionData = ref(null)
const aiRawText = ref('') // 保存 AI 原始文本

const sampleFoods = ref([
  { name: '苹果', emoji: '🍎' },
  { name: '香蕉', emoji: '🍌' },
  { name: '西兰花', emoji: '🥦' },
  { name: '鸡胸肉', emoji: '🍗' },
  { name: '牛奶', emoji: '🥛' },
  { name: '鸡蛋', emoji: '🥚' },
  { name: '面包', emoji: '🍞' },
  { name: '米饭', emoji: '🍚' }
])

/** 调用 AI 接口识别食物 */
const callAI = (prompt, imageBase64 = null) => {
  isAnalyzing.value = true

  const requestData = {
    model: 'openai/gpt-4.1',
    max_tokens: 512,
    messages: [
      {
        role: 'user',
        content: [
          { type: 'text', text: prompt }
        ]
      }
    ]
  }

  if (imageBase64) {
    requestData.messages[0].content.push({
      type: 'image_url',
      image_url: { url: `data:image/jpeg;base64,${imageBase64}` }
    })
  }

  wx.request({
    url: 'https://openrouter.ai/api/v1/chat/completions',
    method: 'POST',
    header: {
      'Authorization': 'Bearer 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', // 替换成你的 API Key
      'Content-Type': 'application/json'
    },
    data: requestData,
    success: (res) => {
      const aiText = res.data?.choices?.[0]?.message?.content || ''
      console.log('🧠 AI 返回原始内容:', aiText)
      aiRawText.value = aiText

      // 简单解析返回的文本生成 nutritionData
      try {
        nutritionData.value = JSON.parse(aiText)
      } catch (e) {
        wx.showToast({ title: '未识别出食品', icon: 'error' })
      }
    },
    fail: (err) => {
      console.error('AI识别失败:', err)
      wx.showToast({ title: '识别失败', icon: 'error' })
    },
    complete: () => {
      isAnalyzing.value = false
    }
  })
}

/** 拍照 */
const takePhoto = () => {
  wx.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sourceType: ['camera'],
    success: (res) => handleSelectedImage(res.tempFiles[0].tempFilePath)
  })
}

/** 相册选择 */
const chooseImage = () => {
  wx.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sourceType: ['album'],
    success: (res) => handleSelectedImage(res.tempFiles[0].tempFilePath)
  })
}

/** 处理选择的图片：读取为 Base64 并调用 AI */
const handleSelectedImage = (filePath) => {
  selectedImage.value = filePath

  const fs = wx.getFileSystemManager()
  fs.readFile({
    filePath,
    encoding: 'base64',
    success: (res) => callAI(
      '请识别这张图片中的食物，并返回详细营养信息（每100克含量）和健康建议，返回 JSON 格式，字段包括：name, calories, protein, carbs, fat, fiber, sugar, sodium, advice',
      res.data
    ),
    fail: () => wx.showToast({ title: '图片读取失败', icon: 'error' })
  })
}

/** 点击图片放大预览 */
const previewImage = () => {
  if (!selectedImage.value) return
  wx.previewImage({
    urls: [selectedImage.value],
    current: selectedImage.value
  })
}

/** 重置 */
const resetAnalysis = () => {
  selectedImage.value = null
  nutritionData.value = null
  aiRawText.value = ''
}

/** 格式化 AI 文本：加粗 & 列表 */
const formattedLines = computed(() => {
  if (!aiRawText.value) return []

  const lines = aiRawText.value.split('\n')
  return lines.map(line => {
    const parts = []
    const regex = /\*\*(.+?)\*\*/g
    let lastIndex = 0
    let match
    while ((match = regex.exec(line)) !== null) {
      if (match.index > lastIndex) parts.push({ text: line.slice(lastIndex, match.index), bold: false })
      parts.push({ text: match[1], bold: true })
      lastIndex = match.index + match[0].length
    }
    if (lastIndex < line.length) parts.push({ text: line.slice(lastIndex), bold: false })
    parts.forEach(p => { if (!p.bold) p.text = p.text.replace(/^\s*[-–—]\s+/gm, '• ') })
    return { parts }
  })
})

/** 常见食物选择 */
const selectSampleFood = (food) => {
  wx.showToast({ title: `选择了${food.name}`, icon: 'none' })
  callAI(`请提供 "${food.name}" 的营养成分和健康建议，返回 JSON 格式，字段包括：name, calories, protein, carbs, fat, fiber, sugar, sodium, advice`)
}

/** 保存记录 */
const saveRecord = () => {
  wx.showToast({ title: '已保存到饮食记录', icon: 'success' })
}

/** 分享结果 */
const shareResult = () => {
  wx.showShareMenu({ withShareTicket: true })
}

/** 计算进度条百分比 */
const getProgressValue = (value, max) => Math.min((value / max) * 100, 100)
</script>


<style scoped>
.food-recognition {
  min-height: 100vh;
  background: #f9fafb;
  padding: 32rpx;
}

.page-header {
  margin-bottom: 48rpx;
}

.page-title {
  font-size: 40rpx;
  font-weight: 600;
  color: #1f2937;
  display: block;
  margin-bottom: 8rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
}

.upload-section {
  background: white;
  border-radius: 24rpx;
  padding: 48rpx;
  margin-bottom: 48rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.upload-area {
  text-align: center;
}

.upload-icon {
  font-size: 96rpx;
  margin-bottom: 32rpx;
}

.upload-title {
  font-weight: 500;
  color: #1f2937;
  display: block;
  margin-bottom: 16rpx;
  font-size: 32rpx;
}

.upload-subtitle {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 32rpx;
}

.upload-buttons {
  display: flex;
  gap: 16rpx;
  justify-content: center;
}

.upload-btn {
  padding: 24rpx 32rpx;
  border-radius: 16rpx;
  transition: all 0.2s;
}

.upload-btn.primary {
  background: #10b981;
}

.upload-btn.primary:active {
  background: #059669;
}

.upload-btn.secondary {
  background: white;
  border: 1px solid #d1d5db;
}

.upload-btn.secondary:active {
  background: #f9fafb;
}

.btn-text {
  font-size: 28rpx;
  color: white;
}

.upload-btn.secondary .btn-text {
  color: #374151;
}

.image-preview {
  text-align: center;
}

.preview-image {
  width: 100%;
  height: 384rpx;
  border-radius: 16rpx;
  margin-bottom: 32rpx;
}

.analyzing {
  margin: 32rpx 0;
}

.spinner {
  width: 64rpx;
  height: 64rpx;
  border: 4rpx solid #e5e7eb;
  border-top: 4rpx solid #10b981;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.analyzing-text {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
}

.reset-btn {
  background: white;
  border: 1px solid #d1d5db;
  padding: 16rpx 32rpx;
  border-radius: 16rpx;
  display: inline-block;
  transition: all 0.2s;
}

.reset-btn:active {
  background: #f9fafb;
}

.reset-text {
  font-size: 28rpx;
  color: #374151;
}

.nutrition-results {
  background: white;
  border-radius: 24rpx;
  padding: 48rpx;
  margin-bottom: 48rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.result-header {
  margin-bottom: 32rpx;
}

.result-title {
  font-weight: 600;
  color: #1f2937;
  font-size: 32rpx;
  display: block;
}

.food-info {
  text-align: center;
  margin-bottom: 48rpx;
}

.food-name {
  font-size: 36rpx;
  font-weight: 600;
  color: #1f2937;
  display: block;
  margin-bottom: 16rpx;
}

.calories {
  font-size: 64rpx;
  font-weight: bold;
  color: #10b981;
  display: block;
  margin-bottom: 8rpx;
}

.serving {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
}

.nutrition-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx;
  margin-bottom: 32rpx;
}

.nutrition-item {
  margin-bottom: 16rpx;
}

.nutrition-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.nutrition-label {
  font-size: 28rpx;
  color: #6b7280;
}

.nutrition-value {
  font-weight: 500;
  color: #1f2937;
  font-size: 28rpx;
}

.progress-bar {
  width: 100%;
  height: 16rpx;
  background: #e5e7eb;
  border-radius: 8rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 8rpx;
  transition: width 0.3s ease;
}

.progress-fill.protein {
  background: #3b82f6;
}

.progress-fill.carbs {
  background: #f59e0b;
}

.progress-fill.fat {
  background: #ef4444;
}

.progress-fill.fiber {
  background: #10b981;
}

.additional-info {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
  margin-bottom: 32rpx;
}

.info-tag {
  background: #f3f4f6;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
}

.tag-text {
  color: #6b7280;
  font-size: 24rpx;
}

.health-advice {
  background: #f0fdf4;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 32rpx;
}

.advice-title {
  font-weight: 500;
  color: #166534;
  display: block;
  margin-bottom: 8rpx;
  font-size: 28rpx;
}

.advice-text {
  font-size: 28rpx;
  color: #15803d;
  line-height: 1.6;
  display: block;
}

.action-buttons {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 16rpx;
  text-align: center;
  transition: all 0.2s;
}

.action-btn.primary {
  background: #10b981;
}

.action-btn.primary:active {
  background: #059669;
}

.action-btn.secondary {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.action-btn.secondary:active {
  background: #e5e7eb;
}

.action-btn.primary .btn-text {
  color: white;
}

.action-btn.secondary .btn-text {
  color: #374151;
}

.sample-foods {
  margin-bottom: 48rpx;
}

.sample-title {
  font-weight: 600;
  color: #1f2937;
  display: block;
  margin-bottom: 24rpx;
  font-size: 32rpx;
}

.foods-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24rpx;
}

.food-item {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  text-align: center;
  transition: all 0.2s;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.food-item:active {
  transform: scale(0.95);
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.15);
}

.food-emoji {
  font-size: 64rpx;
  display: block;
  margin-bottom: 16rpx;
}

.food-name {
  font-size: 24rpx;
  color: #6b7280;
  display: block;
}
</style>
